<template>
  <scroll-view
    class="scroll-x"
    scroll-x
    :class="ggclass"
    :show-scrollbar="false"
    enhanced
    scroll-with-animation
    :scroll-into-view="`item${tabIndex < 2 ? 0 : tabIndex - 1}`"
  >
    <view
      class="tab-tag grey font-weight"
      :class="{ pitch: tabIndex === index, disabled: item.disabled }"
      v-for="(item, index) in tabs"
      :key="index"
      :style="{
        width,
        height,
        fontSize,
        color: tabIndex === index ? pitchColor : '',
      }"
      :id="`item${index}`"
      @click="tabChange(index, item)"
    >
      {{ item.name }}
    </view>
  </scroll-view>
</template>

<script setup lang="ts">
import { defineProps, onMounted, reactive, toRefs, watch } from "vue";
const emit = defineEmits(["change", "update:modelValue"]);
const props = defineProps({
  pitchColor: {
    type: String,
    default: "",
  },
  fontSize: {
    type: String,
    default: "",
  },
  width: {
    type: String,
    default: "",
  },
  height: {
    type: String,
    default: "",
  },
  modelValue: {
    // default: 0,
    type: [Number, String],
  },
  ggclass: {
    type: String,
    default: "",
  },
  tabs: {
    type: Array<any>,
    default: () => [],
  },
  display: Boolean,
  immediate: {
    type: Boolean,
    default: false,
  },
});
watch(
  () => props.modelValue,
  (v) => {
    state.tabIndex = props.tabs.findIndex((a: any) => a.id == v);
  },
  { immediate: true }
);

const state = reactive({
  tabIndex: 0,
});
const { tabIndex } =toRefs(state);
onMounted(() => {
  if (props.immediate) {
    tabChange(0, props.tabs[0]);
  }
});

const tabChange = (index: number, item: any) => {
  state.tabIndex = index;
  if (index < 0) {
    return emit("change");
  }
  emit("change", item.id);
  emit("update:modelValue", item.id);
};
</script>

<style scoped lang="scss">
.scroll-x {
  white-space: nowrap;
}

.tab-tag {
  height: 64rpx;
  border-radius: 10rpx;
  display: inline-flex;
  flex-wrap: nowrap;
  justify-content: center;
  align-items: center;
  padding: 0 24rpx;
  z-index: 1;
  color: #979797;
  border-radius: 12rpx;
  margin-right: 24rpx;
  font-size: 28rpx;

  &.disabled {
    background: #f4f4f4;
    color: #c8c8c8;
    pointer-events: none;
  }
}

.pitch {
  position: relative;
  font-weight: 600;
  &::after {
    position: absolute;
    content: "";
    width: 40rpx;
    height: 5rpx;
    background: $uni-color-main;
    bottom: 0;
  }
}
</style>